import ApiSystemDictData from '@/services/system/ApiSystemDictData';
import { useSessionStorageState } from 'ahooks';
import { useEffect } from 'react';

export type DictValue = {
  dictType: string;
  dictValue: string;
  dictLabel: string;
  dictSort: number;
};

const useDict = (typeCode: string) => {
  // 使用session管理缓存数据, 每次关闭浏览器后数据会被清空
  const [dict, setDict] = useSessionStorageState<DictValue[]>(
    `DICT:${typeCode}`,
    { defaultValue: [] },
  );

  const fetchDict = async () => {
    const data = await ApiSystemDictData.listByType(typeCode);
    setDict(data);
  };
  useEffect(() => {
    if (dict?.length === 0) {
      // 如果还没有加载过 则去加载一次
      fetchDict()
        .then()
        .catch(() => {});
    }
  }, [typeCode]);

  return [dict];
};

export default useDict;
